package com.apcc4m.sfpushbatch.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.stereotype.Service;

import com.apcc4m.sfpushbatch.config.SfpushJobConfig;

@Service
public class BatchManagerService {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job notificationJob1;
    @Autowired
    private Job pushStatusJob1;
    
    
    private boolean  isNotificationJobRunning = false;
    private boolean isPushStatusJobRunning = false;
    
    public void executeNotificationJob() throws Exception {
        System.out.println("executeNotificationJob " + isNotificationJobRunning);
        if (isNotificationJobRunning) {
            return;
        }
        // spring batch的job需要指定不一样的参数才可以重新启动一个已经完成的job
        Map<String, JobParameter> confMap = new HashMap<String, JobParameter>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));
        isNotificationJobRunning = true;
        // 启动job后会一直堵塞至job结束，同一个job要到运行结束才可以再次运行
        JobExecution jobExecution = jobLauncher.run(notificationJob1, new JobParameters(confMap));
        isNotificationJobRunning = false;
        System.out.println(jobExecution.getExitStatus());
    }

    public void executePushStatusJob() throws Exception {
        System.out.println("executePushStatusJob " + isPushStatusJobRunning);
        if (isPushStatusJobRunning) {
            return;
        }
        // spring batch的job需要指定不一样的参数才可以重新启动一个已经完成的job
        Map<String, JobParameter> confMap = new HashMap<String, JobParameter>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));
        isPushStatusJobRunning = true;
        // 启动job后会一直堵塞至job结束，同一个job要到运行结束才可以再次运行
        JobExecution jobExecution = jobLauncher.run(pushStatusJob1, new JobParameters(confMap));
        isPushStatusJobRunning = false;
        System.out.println(jobExecution.getExitStatus());
    }
}
